


#!/bin/bash 
if [ $# -ne 4  ]; then 
    echo "字段个数不正确，请检查"
    exit 1
fi 

source_table=$1
target_field=$2
target_type=$3
output_table=$4
current_date_str=$(date +%Y-%m-%d)

logic=""

if [ "$target_type" == "phone" ] ; then 
    logic="case when (nvl($target_field, '') = '') then '' 
    when (length($target_field) < 7) then $target_field 
    else concat(substr($target_field, 1, 3), repeat('*', length($target_field) - 6), substr($target_field, length($target_field) - 2, 3)) 
    end as $target_field"
elif [[ "$target_type" =~ ^(CUST_NAME|REMITTER_NAME|BENEFICIARY_NAME|UBO_NAME|NAME|ALIAS_NAME|TARGET_NAME)$ ]]; then 
    echo "匹配姓名字段，执行脱敏"
    logic="case when (nvl($target_field, '') = '') then '' 
    when (length($target_field) >= 2) then concat(substr($target_field, 1, 1), repeat('*', length($target_field) - 1)) 
    else $target_field 
    end as $target_field"
else 
    echo "不支持的脱敏类型：$target_type"
    exit 1 
fi 

# 提取源表字段时，排除分区字段和etl_date（避免与目标表分区列重复）
Field_Str=$(hive -S -e "desc $source_table;" | awk '
    BEGIN { flag=1 } 
    /^# Partition Information/ { flag=0 }
    # 排除空行、注释行、etl_date字段（因目标表中是分区列）
    flag==1 && $1 !~ /^$/ && $1 !~ /^#/ && $1 != "etl_date" { print $1 }
' | tr '\n' ',' | sed 's/,$//')

if [[ -z "$Field_Str" ]]; then
    echo "错误：源表 $source_table 字段提取失败"
    exit 1
fi
if [[ ! "$Field_Str" =~ "$target_field" ]]; then
    echo "错误：源表 $source_table 中不存在字段 $target_field"
    exit 1
fi

Select_Clause=""
IFS=',' read -ra FIELDS <<< "$Field_Str"
for field in "${FIELDS[@]}"; do
    if [ "$field" = "$target_field" ]; then
        Select_Clause="${Select_Clause}${logic},"
    else
        Select_Clause="${Select_Clause}${field},"
    fi
done
Select_Clause=$(echo "$Select_Clause" | sed 's/,$//')

hql_str="
set hive.exec.dynamic.partition.mode=nonstrict;
INSERT INTO TABLE $output_table 
PARTITION (etl_date)
SELECT $Select_Clause, '$current_date_str' AS etl_date
FROM $source_table;
"

echo "================ 开始执行脱敏 ================"
echo "源表名：$source_table"
echo "待脱敏字段：$target_field"
echo "脱敏类型：$target_type"
echo "输出表名：$output_table"
echo "执行的HQL语句：$hql_str"
echo "=============================================="

hive -e "$hql_str"

if [ $? -eq 0 ]; then 
    echo "脱敏成功"
else 
    echo "脱敏失败，请检查"
    exit 1
fi
